package com.example.jwtdemo.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.jwtdemo.pojo.User;
import com.example.jwtdemo.service.UserService;
import com.example.jwtdemo.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author HMQ
 * @date 2020/9/20 14:29
 */
@RestController
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @GetMapping("/user/login")
    public Map<String, Object> login(User user) {
        log.info("用户名：[{}]", user.getUserId());
        log.info("密码：[{}]", user.getPassword());
        Map<String, Object> map = new HashMap<>(3);
        try {
            User userDb = userService.login(user);
            Map<String, String> payload = new HashMap<>(2);
            payload.put("userId", userDb.getUserId());
            payload.put("userName", userDb.getName());
            String token = JwtUtil.getToken(payload);
            map.put("state", true);
            map.put("msg", "认证成功");
            map.put("token", token);
        } catch (Exception e) {
            map.put("state", false);
            map.put("msg", e.getMessage());
        }
        return map;
    }

    /**
     * 业务接口
     * @param request 请求
     * @return 业务所需内容
     */
    @PostMapping("/user/test")
    public Map<String, Object> test(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        map.put("state", true);
        map.put("msg", "登陆成功");
        String token = request.getHeader("token");
        //此时经过拦截器处理后token肯定是正确的
        DecodedJWT verify = JwtUtil.vertify(token);
        log.info("userId:[{}]", verify.getClaim("userId").asString());
        log.info("userName:[{}]", verify.getClaim("userName").asString());
        map.put("token", token);
        return map;
    }
}
